<template>
    <el-card class="box-card">

        <!-- 新增/修改弹出框 -->
        <el-dialog @opened="handleBeforeOpen" :title="dialogTitle + '友链'" :visible.sync="dialogAddOrUpdate" width="40%"
            :before-close="handleCloseAdd">
            <el-form :model="linkForm" :rules="linkFormRules" ref="linkForm" label-width="100px">

                <el-form-item label="友链头像" prop="linkAvatar">
                    <my-upload-img ref="upload" url="/links/upload" @upload-success="handleUploadSuccess"
                        :imageUrl="linkForm.linkAvatar" />
                </el-form-item>

                <el-form-item label="友链名称" prop="linkName">
                    <el-input v-model="linkForm.linkName"></el-input>
                </el-form-item>

                <el-form-item label="友链地址" prop="linkAddress">
                    <el-input v-model="linkForm.linkAddress"></el-input>
                </el-form-item>

                <el-form-item label="友链介绍" prop="linkIntro">
                    <el-input type="textarea" v-model="linkForm.linkIntro"></el-input>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="submitAddOrUpdateForm('linkForm')">立即{{ dialogTitle }}</el-button>
                    <el-button @click="resetForm('linkForm')">重置</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>

        <!-- 搜索栏 -->
        <div class="select-div">
            <el-form :inline="true" style="height: 40px">
                <el-form-item>
                    <el-input clearable v-model="condition.keywords" prefix-icon="el-icon-search" size="small"
                        placeholder="请输入友链名称关键字" style="width:200px" @keyup.enter.native="searchLinks" />
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" size="small" icon="el-icon-search" @click="searchLinks">搜索</el-button>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" size="small" icon="el-icon-plus" @click="dialogAdd">新增</el-button>
                </el-form-item>

                <el-form-item>
                    <el-button type="danger" size="small" icon="el-icon-delete" @click="deleteCheck()"
                        :disabled="this.selection.length === 0">删除选中
                    </el-button>
                </el-form-item>
            </el-form>
        </div>

        <!-- 表格内容 -->
        <el-table ref="multipleTable" :data="tableData" border :header-cell-style="{ 'text-align': 'center' }"
            :cell-style="{ 'text-align': 'center' }" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"></el-table-column>

            <el-table-column prop="linkAvatar" label="友链头像">
                <template slot-scope="scope">
                    <el-image style="width: 100px;height: 100px" :src="scope.row.linkAvatar" />
                </template>
            </el-table-column>

            <el-table-column prop="linkName" label="友链名称" sortable></el-table-column>

            <el-table-column prop="linkAddress" label="友链地址">
                <template slot-scope="scope">
                    <el-link type="primary" :href="scope.row.linkAddress" target="_blank">{{ scope.row.linkAddress
                        }}</el-link>
                </template>
            </el-table-column>

            <el-table-column prop="linkIntro" label="友链介绍"></el-table-column>

            <el-table-column prop="createTime" label="创建时间" sortable></el-table-column>

            <el-table-column label="操作" fixed="right" width="100">
                <template slot-scope="scope">
                    <el-tooltip effect="dark" content="编辑" placement="top-start">
                        <el-button circle icon="el-icon-edit" size="mini" @click="dialogUpdate(scope.row.id)" />
                    </el-tooltip>

                    <el-tooltip effect="dark" content="删除" placement="top-start">
                        <el-button circle icon="el-icon-delete" size="mini" type="danger"
                            @click="deleteCheck(scope.row.id)" />
                    </el-tooltip>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <pagination :total="total" :page_index="pageNum" @pageChange="pageChange" />

    </el-card>
</template>

<script>
import { linksApi } from '@/api';

export default {
    data() {
        return {
            tableData: [],
            selection: [],
            linkForm: {},
            total: 0,
            pageNum: 1,
            pageSize: 10,
            dialogAddOrUpdate: false,
            dialogTitle: '',
            condition: {
                keywords: null
            },
            linkFormRules: {
                linkName: [
                    { required: true, message: '请输入友链名称', trigger: 'blur' }
                ],
                linkAvatar: [
                    { required: true, message: '请上传友链头像', trigger: 'blur' }
                ],
                linkAddress: [
                    { required: true, message: '请输入友链地址', trigger: 'blur' }
                ],
                linkIntro: [
                    { required: true, message: '请输入友链介绍', trigger: 'blur' }
                ]
            }
        }
    },

    methods: {
        handleSelectionChange(selection) {
            this.selection = selection.map(item => item.id)
        },

        pageChange(val) {
            this.pageNum = val.pageNum;
            this.pageSize = val.pageSize;
            this.loadLinkList();
        },

        searchLinks() {
            this.pageNum = 1;
            this.loadLinkList();
        },

        dialogAdd() {
            this.dialogTitle = "新增";
            this.dialogAddOrUpdate = true;
        },

        handleBeforeOpen() {
            this.$refs.upload.restFile();
        },

        handleCloseAdd() {
            this.$refs.linkForm.resetFields();
            this.linkForm = {};
            this.dialogAddOrUpdate = false;
        },

        handleUploadSuccess(data) {
            this.linkForm.linkAvatar = data.data;
        },

        resetForm(formName) {
            this.$refs[formName].resetFields();
            this.linkForm = {};
        },

        submitAddOrUpdateForm(formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    const apiMethod = this.linkForm.id ? linksApi.updateLink : linksApi.addLink;
                    apiMethod(this.linkForm).then((response) => {
                        if (response.data.code === 20000) {
                            this.$message({
                                showClose: true,
                                message: '操作成功！',
                                type: 'success',
                                onClose: () => {
                                    this.loadLinkList();
                                }
                            });
                        }
                    });
                    this.dialogAddOrUpdate = false;
                    this.resetForm(formName);
                } else {
                    return false;
                }
            })
        },

        deleteCheck(id) {
            this.$confirm("删除后不可恢复", "提示", {
                type: "warning"
            }).then(() => {
                const ids = id == null ? this.selection : [id];
                linksApi.deleteLinks(ids).then((response) => {
                    if (response.data.code === 20000) {
                        this.$message.success("友链删除成功！");
                        this.loadLinkList();
                    }
                });
            }).catch(() => {
                // 取消删除操作
            });
        },

        dialogUpdate(id) {
            linksApi.getLinkInfo(id).then((response) => {
                if (response.data.code === 20000) {
                    this.linkForm = response.data.data;
                    this.dialogTitle = "修改";
                    this.dialogAddOrUpdate = true;
                }
            });
        },

        loadLinkList() {
            const params = {
                pageNum: this.pageNum,
                pageSize: this.pageSize,
                keywords: this.condition.keywords
            };
            
            linksApi.getLinkList(params).then((response) => {
                if (response.data.code === 20000) {
                    if (response.data.data != null) {
                        this.tableData = response.data.data.pagingList;
                        this.total = response.data.data.count;
                        return;
                    }
                    this.tableData = null;
                    this.total = null;
                }
            }).catch((error) => {
                this.$message.error("获取友链列表失败！");
            });
        }
    },

    created() {
        this.loadLinkList();
    }
}
</script>

<style scoped></style>